package cn.kgc.vue.controller;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.service.TemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author 课工场
 * @date 2024/4/19
 * @description 资源中心
 */
@RestController
@RequestMapping("resources")
@Api(tags = "资源中心")
public class ResourcesController {

    @Resource
    private TemplateService templateService;

    @PostMapping("page")
    @ApiOperation("资源分页")
    public ResponseResult resourcesPage(@RequestBody QueryCondition<Template> queryCondition) {

        return templateService.resourcesPage(queryCondition);
    }


    @PostMapping("upload")
    @ApiOperation("资源上传")
    public ResponseResult uploadResources(MultipartFile file) {
        // 文件的名字  文件的大小
        return templateService.upload(file);
    }


    @GetMapping("download/{uuid}")
    @ApiOperation("资源下载")
    public void downloadResources(HttpServletResponse response, @PathVariable("uuid") String uuid) {

        File file = new File("D:/upload/springboot/" + uuid);
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @PostMapping("add")
    @ApiOperation("添加资源名称")
    public ResponseResult addResourcesInfo(@RequestBody Template template) {
        // 文件的名字  文件的大小
        templateService.save(template);
        return ResponseResult.success().message("资源发布成功");
    }

    @DeleteMapping("delete/{uuid}")
    @ApiOperation("删除资源")
    public ResponseResult deleteResourcesInfo(@PathVariable("uuid") String uuidName) {

        // 删除资源信息
        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(Template::getUuidName, uuidName);
        templateService.remove(lambda);
        // 删除文件资源
        File file = new File("D:/upload/springboot/" + uuidName);
        file.delete();

        return ResponseResult.success().message("删除成功");
    }

}
